//
//  ShelfViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/29.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "ShelfViewController.h"
#import "MagazineCollectionViewCell.h"
#import "BookCollectionViewCell.h"
#import "BookReadingViewController.h"
#import "BookDetailViewController.h"
#import "MagazineDetailViewController.h"

@interface ShelfViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** backScrollView */
@property (nonatomic, strong) UIScrollView * backScrollView;
/** 电子书按钮 */
@property (nonatomic, strong) UIButton * bookButton;
/** 期刊按钮 */
@property (nonatomic, strong) UIButton * magazineButton;
/** 电子书列表 */
@property (nonatomic, strong) UICollectionView * bookCollectionView;
/** 期刊列表 */
@property (nonatomic, strong) UICollectionView * magazineCollectionView;
/** 电子书列表布局 */
@property (nonatomic, strong) UICollectionViewFlowLayout * bookFlowLayout;
/** 期刊列表 */
@property (nonatomic, strong) UICollectionViewFlowLayout * magazineFlowLayout;
/** 书数据源 */
@property (nonatomic, strong) NSMutableArray * bookArr;
/** 期刊数据源 */
@property (nonatomic, strong) NSMutableArray * magazineArr;
/** 中间的竖线 */
@property (nonatomic, strong) UIImageView * vLine;
/** 下划线 */
@property (nonatomic, strong) UIImageView * hLine;
/** 删除按钮 */
@property (nonatomic, strong) UIButton * deleteButton;

@end

@implementation ShelfViewController

- (UIButton *)deleteButton{
    if (!_deleteButton) {
        _deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(WidthScale(100) - 25, 0, 25, 24)];
        [_deleteButton setImage:ImageNamed(@"shanchu") forState:UIControlStateNormal];
    }
    return _deleteButton;
}

- (NSMutableArray *)magazineArr{
    if (!_magazineArr) {
        _magazineArr = [NSMutableArray array];
    }
    return _magazineArr;
}

- (NSMutableArray *)bookArr{
    if (!_bookArr) {
        _bookArr = [NSMutableArray array];
    }
    return _bookArr;
}

- (UICollectionViewFlowLayout *)magazineFlowLayout{
    if (!_magazineFlowLayout) {
        _magazineFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _magazineFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _magazineFlowLayout;
}

- (UICollectionView *)magazineCollectionView{
    if (!_magazineCollectionView) {
        _magazineCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(SCREEN_W, 0, SCREEN_W, self.backScrollView.frame.size.height) collectionViewLayout:self.magazineFlowLayout];
        _magazineCollectionView.delegate = self;
        _magazineCollectionView.dataSource = self;
        _magazineCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [_magazineCollectionView registerClass:[MagazineCollectionViewCell class] forCellWithReuseIdentifier:@"magazineCell"];
    }
    return _magazineCollectionView;
}

- (UIButton *)magazineButton{
    if (!_magazineButton) {
        _magazineButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W / 2, 64, SCREEN_W / 2, HeightScale(44))];
        [_magazineButton setTitle:@"期刊" forState:UIControlStateNormal];
        [_magazineButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_magazineButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _magazineButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_magazineButton initWithBlock:^(id obj) {
            DLog(@"期刊");
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.backScrollView.contentOffset = CGPointMake(SCREEN_W, 0);
                weakSelf.hLine.center = CGPointMake(weakSelf.backScrollView.contentOffset.x / 2 + SCREEN_W / 4, weakSelf.hLine.center.y);
            }];
            
        } for:UIControlEventTouchUpInside];
    }
    return _magazineButton;
}

- (UICollectionViewFlowLayout *)bookFlowLayout{
    if (!_bookFlowLayout) {
        _bookFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        _bookFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    }
    return _bookFlowLayout;
}

- (UICollectionView *)bookCollectionView{
    if (!_bookCollectionView) {
        _bookCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, self.backScrollView.frame.size.height) collectionViewLayout:self.bookFlowLayout];
        _bookCollectionView.delegate = self;
        _bookCollectionView.dataSource = self;
        _bookCollectionView.backgroundColor = COLOR_LIGHTBGCOLOR;
        [_bookCollectionView registerClass:[BookCollectionViewCell class] forCellWithReuseIdentifier:@"bookCell"];
    }
    return _bookCollectionView;
}

- (UIImageView *)hLine{
    if (!_hLine) {
        _hLine = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W / 2 - WidthScale(30)) / 2, 64 + HeightScale(44) - HeightScale(2), WidthScale(30), HeightScale(2))];
        _hLine.image =ImageNamed(@"liulanlishi_xian");
    }
    return _hLine;
}

- (UIImageView *)vLine{
    if (!_vLine) {
        _vLine = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W - 1) / 2, 64 + HeightScale(10), 1, HeightScale(24))];
        _vLine.image = ImageNamed(@"liulanlishifenge");
    }
    return _vLine;
}

- (UIButton *)bookButton{
    if (!_bookButton) {
        _bookButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 64, SCREEN_W / 2, HeightScale(44))];
        [_bookButton setTitle:@"电子书" forState:UIControlStateNormal];
        [_bookButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        [_bookButton setTitleColor:COLOR_GREEN forState:UIControlStateSelected];
        _bookButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_bookButton initWithBlock:^(id obj) {
            DLog(@"电子书");
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.backScrollView.contentOffset = CGPointMake(0, 0);
                weakSelf.hLine.center = CGPointMake(weakSelf.backScrollView.contentOffset.x / 2 + SCREEN_W / 4, weakSelf.hLine.center.y);
            }];
            
        } for:UIControlEventTouchUpInside];
    }
    return _bookButton;
}

- (UIScrollView *)backScrollView{
    if (!_backScrollView) {
        _backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64 + HeightScale(44), SCREEN_W, SCREEN_H - 64 - HeightScale(44))];
        _backScrollView.contentSize = CGSizeMake(SCREEN_W * 2, _backScrollView.frame.size.height);
        _backScrollView.pagingEnabled = YES;
        _backScrollView.delegate = self;
        _backScrollView.showsHorizontalScrollIndicator = NO;
    }
    return _backScrollView;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
    }
    return _navBar;
}

#pragma mark - lify cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"我的书架";
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    
    [self.view addSubview:self.navBar];
    
    [self.view addSubview:self.bookButton];
    
    [self.view addSubview:self.magazineButton];
    
    [self.view addSubview:self.hLine];
    
    [self.view addSubview:self.vLine];
    
    [self.view addSubview:self.backScrollView];
    
    [self.backScrollView addSubview:self.magazineCollectionView];
    
    [self.backScrollView addSubview:self.bookCollectionView];
    
    [self requestGetShelfOfBook];
    
    [self requestGetShelfOfMagazine];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc{
    DLog(@"%s", __func__);
}

#pragma mark - UICollectionViewDelegate & UICollectionViewDataSource Methods

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([collectionView isEqual:self.bookCollectionView]) {
        return self.bookArr.count;
    } else {
        return self.magazineArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView isEqual:self.bookCollectionView]) {
        BookCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"bookCell" forIndexPath:indexPath];
        
        //添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showDeleteButton:)];
        longPress.minimumPressDuration = 0.5;
        [cell addGestureRecognizer:longPress];
        
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.bookArr[indexPath.row][@"coverImageFile"]]] placeholderImage:ImageNamed(@"placeholdershuji")];
        cell.titleLabel.text = self.bookArr[indexPath.row][@"name"];
        cell.authorLabel.text = self.bookArr[indexPath.row][@"author"];
        cell.bookID = [self.bookArr[indexPath.row][@"id"] integerValue];
        
        return cell;
    } else {
        MagazineCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"magazineCell" forIndexPath:indexPath];
        
        //添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showDeleteButton:)];
        longPress.minimumPressDuration = 1.0;
        [cell addGestureRecognizer:longPress];
        
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.magazineArr[indexPath.row][@"coverimgpath"]]] placeholderImage:ImageNamed(@"placeholdershuji")];
        cell.titleLabel.text = self.magazineArr[indexPath.row][@"periodicalName"];
        cell.authorLabel.text = self.magazineArr[indexPath.row][@"issuename"];
        cell.magazineID = [self.magazineArr[indexPath.row][@"issueid"] integerValue];
        
        return cell;
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView isEqual:self.magazineCollectionView]) {
        return CGSizeMake(WidthScale(100), HeightScale(190));
    } else{
        return CGSizeMake(WidthScale(100), HeightScale(190));
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.magazineCollectionView]) {
        return WidthScale(10);
    } else {
        return WidthScale(10);
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.magazineCollectionView]) {
        return HeightScale(10);
    } else {
        return HeightScale(10);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if ([collectionView isEqual:self.magazineCollectionView]) {
        return UIEdgeInsetsMake(HeightScale(20), WidthScale(20), HeightScale(20), WidthScale(20));
    } else {
        return UIEdgeInsetsMake(HeightScale(20), WidthScale(20), HeightScale(20), WidthScale(20));
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"%ld", indexPath.row);
    
    if ([collectionView isEqual:self.bookCollectionView]) {
        //电子书
        NSString *filePath = [BooksPath stringByAppendingPathComponent:self.bookArr[indexPath.row][@"name"]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:0]) {
            BookReadingViewController *readingVC = [[BookReadingViewController alloc] init];
            readingVC.native = YES;
            readingVC.isMagazine = NO;
            readingVC.dataDic = self.bookArr[indexPath.row];
            readingVC.filePath = filePath;
            readingVC.pages = [self.bookArr[indexPath.row][@"pages"] integerValue];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:readingVC];
            nav.navigationBar.hidden = YES;
            [self presentViewController:nav animated:YES completion:^{
                
            }];
        } else {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地没有这本书籍，需要下载" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                DLog(@"详情");
                BookDetailViewController *bookDetailVC = [[BookDetailViewController alloc] init];
                bookDetailVC.bookDic = self.bookArr[indexPath.row];
                [self.navigationController pushViewController:bookDetailVC animated:YES];
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }

    } else {
        //期刊
        NSString *filePath = [MagazinesPath stringByAppendingFormat:@"%@%@", self.magazineArr[indexPath.row][@"name"], self.magazineArr[indexPath.row][@"issuename"]];
        if ([[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:0]) {
            BookReadingViewController *readingVC = [[BookReadingViewController alloc] init];
            readingVC.native = YES;
            readingVC.isMagazine = YES;
            readingVC.dataDic = self.magazineArr[indexPath.row];
            readingVC.filePath = filePath;
            readingVC.pages = [self.magazineArr[indexPath.row][@"pages"] integerValue];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:readingVC];
            nav.navigationBar.hidden = YES;
            [self presentViewController:nav animated:YES completion:^{
                
            }];
        } else {
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地没有这本期刊，需要下载" message:nil preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                DLog(@"详情");
//                MagazineDetailViewController *magazineDetailVC = [[MagazineDetailViewController alloc] init];
//                magazineDetailVC.magazineDic = self.magazineArr[indexPath.row];
//                [self.navigationController pushViewController:magazineDetailVC animated:YES];
//            }];
//            [alert addAction:action];
//            [self presentViewController:alert animated:YES completion:nil];
            
            BookReadingViewController *readingVC = [[BookReadingViewController alloc] init];
            readingVC.native = NO;
            readingVC.dataDic = self.magazineArr[indexPath.row];
            readingVC.filePath = self.magazineArr[indexPath.row][@"filepath"];
            readingVC.isMagazine = YES;
            readingVC.pages = [self.magazineArr[indexPath.row][@"pages"] integerValue];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:readingVC];
            nav.navigationBar.hidden = YES;
            [self presentViewController:nav animated:YES completion:^{
                
            }];
        }
        
 
        
    }
    
    
    
    
}

#pragma mark - UIScrollViewDelegate Method

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.backScrollView]) {
        self.hLine.center = CGPointMake(scrollView.contentOffset.x / 2 + SCREEN_W / 4, self.hLine.center.y);
        
        if (scrollView.contentOffset.x < - 50) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

#pragma mark - 事件处理

- (void)showDeleteButton:(UILongPressGestureRecognizer *)longPress{
    DLog(@"%@", longPress.view);
    
    if (longPress.state != UIGestureRecognizerStateBegan)
    {
        return;
    } else {
        if ([self.deleteButton superview]) {
            [self.deleteButton removeFromSuperview];
        } else {
            if ([longPress.view isKindOfClass:[BookCollectionViewCell class]]) {
                BookCollectionViewCell *cell = (BookCollectionViewCell *)longPress.view;
                [cell addSubview:self.deleteButton];
                
                NSIndexPath *indexPath = [self.bookCollectionView indexPathForCell:cell];
                
                __weak typeof(self)weakSelf = self;
                [self.deleteButton initWithBlock:^(UIButton *deleteButton) {
                    DLog(@"删除");
                    [weakSelf requestDeleteShelf:1 ID:cell.bookID Name:cell.titleLabel.text Index:indexPath.row];
                    
                    [deleteButton removeFromSuperview];
                    
                } for:UIControlEventTouchUpInside];
            } else {
                MagazineCollectionViewCell *cell = (MagazineCollectionViewCell *)longPress.view;
                [cell addSubview:self.deleteButton];
                
                NSIndexPath *indexPath = [self.magazineCollectionView indexPathForCell:cell];
                
                __weak typeof(self)weakSelf = self;
                [self.deleteButton initWithBlock:^(UIButton *deleteButton) {
                    DLog(@"删除");
                    [weakSelf requestDeleteShelf:4 ID:cell.magazineID Name:[cell.titleLabel.text stringByAppendingString:cell.authorLabel.text] Index:indexPath.row];
                    
                    [deleteButton removeFromSuperview];
                    
                } for:UIControlEventTouchUpInside];
            }
        }
    }
}

#pragma mark - data request

- (void)requestGetShelfOfBook{
    NSString *URL = [NSString stringWithFormat:KgetShelf, KHostAddress, @(1), KOrganizationID, [AppDelegate shareDelegate].userModel.userId, @(1), @(100)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取电子书成功");
        
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                [self.bookArr addObjectsFromArray:responseObject[@"data"][@"items"]];
                [self.bookCollectionView reloadData];
            }
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

- (void)requestGetShelfOfMagazine{
    NSString *URL = [NSString stringWithFormat:KgetShelf, KHostAddress, @(4), KOrganizationID, [AppDelegate shareDelegate].userModel.userId, @(1), @(100)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"获取期刊成功");
            if (![responseObject[@"data"] isKindOfClass:[NSNull class]]) {
                [self.magazineArr addObjectsFromArray:responseObject[@"data"][@"items"]];
                [self.magazineCollectionView reloadData];
            }
            
            
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

- (void)requestDeleteShelf:(NSInteger )type ID:(NSInteger)ID Name:(NSString *)name Index:(NSUInteger)index{
    NSString *URL = [NSString stringWithFormat:KdeleteShelf, KHostAddress, @(type), @(ID), [AppDelegate shareDelegate].userModel.userId];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"删除成功");
            if (type == 1) {
                [self.bookArr removeObjectAtIndex:index];
                [self.bookCollectionView reloadData];
                NSString *bookPath = [BooksPath stringByAppendingPathComponent:name];
                [[NSFileManager defaultManager] removeItemAtPath:bookPath error:nil];
            } else if (type == 4){
                [self.magazineArr removeObjectAtIndex:index];
                [self.magazineCollectionView reloadData];
                NSString *magazinePath = [MagazinesPath stringByAppendingPathComponent:name];
                [[NSFileManager defaultManager] removeItemAtPath:magazinePath error:nil];
            }
            
        } else {
            DLog(@"删除失败");
            [ZRProgressHUD showMsgWithoutView:@"删除失败，请稍后重试"];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

@end
